from flask import Flask, render_template, redirect, url_for, session
from flask_migrate import Migrate
from models.user import db
from auth.auth_service import auth_bp
from auth.log_service import log_bp  # 添加日志服务蓝图

def create_app():
    app = Flask(__name__)
    
    # 配置数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1/logins'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = 'Zmxhc2vmiJHlgL7ogLPlkKznlKjmiLfmja7pn6nlm7126Z2e5bi45ouF5b+D5piv5Lic5pa555Ge6YCa'  # 注意：在生产环境中应该使用更安全的密钥
    
    # 初始化数据库
    db.init_app(app)
    
    # 初始化迁移工具
    migrate = Migrate(app, db)
    
    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(log_bp)  # 注册日志服务蓝图
    
    # 创建默认路由
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # 创建仪表板路由
    @app.route('/dashboard')
    def dashboard():
        # 检查用户是否已登录
        if 'user_id' not in session:
            return redirect(url_for('auth.login'))
        
        return render_template('dashboard.html', username=session.get('username'))
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)